package com.example.safeassistan.home.fragment;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.home.activity.ActivityCheckLog;
import com.example.safeassistan.home.activity.CaptureActivity;
import com.example.safeassistan.home.activity.HiddenDangerinvestigation;

import com.example.safeassistan.home.adapter.BackLogFragmentAdapter;
import com.example.safeassistan.home.model.BackLogFragmentModel;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.utile.EventBusBean;
import com.example.safeassistan.utile.JsonUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.example.safeassistan.constants.Constants.PAGESIZE;

public class BackLogFragment extends BaseVPFragment {
    private static final int REQUEST_CODE = 101;
    private int REQUEST_CODE_SCAN=102;

    private Context context;
    private View view;
    private SmartRefreshLayout refresh;
    private LinearLayout llNodata;
    private BackLogFragmentAdapter adapter;
    private List<BackLogFragmentModel.ResultDTO.RecordsDTO> data;
    private RecyclerView rcView;
    private int type=1;//类型   1未检查 2已检查
    private Integer currentPage=1;
    private String defId="";//	任务检查记录表id
    private Integer count=0;

    private String checkTableId="";//
    private String riskName="";//风险点名称

    private int mPosition=0;

    private String address="";

    public static BackLogFragment newInstance(int  type,String defId,String checkTableId) {
        Bundle arguments = new Bundle();
        arguments.putInt("type",type);
        arguments.putString("defId",defId);
        arguments.putString("checkTableId",checkTableId);
        BackLogFragment fl = new BackLogFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.backlog_second_fragment, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    public void initView(){
        Bundle bundle = getArguments();
         type = bundle.getInt("type");
        defId=bundle.getString("defId");
        checkTableId=bundle.getString("checkTableId");
        address=bundle.getString("address");
        rcView=view.findViewById(R.id.rcView);
        refresh=view.findViewById(R.id.refresh);
        llNodata=view.findViewById(R.id.llNodata);
        setView();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upLoadSuccess(EventBusBean eventBus){
        if (eventBus.getCode()==105){
            riskName=eventBus.getMsg();
            getData();
        }
    }

    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible){
            getData();
        }

        if (isVisible){
            EventBus.getDefault().register(this);
        }else {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onFragmentFirstVisible() { }
    // 获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            map.put("defId",defId);
            map.put("pageNo", String.valueOf(currentPage));
            map.put("pageSize",String.valueOf(PAGESIZE));
            map.put("status",String.valueOf(type));
            if (!riskName.equals("")){
                map.put("riskName",riskName);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.agendaTaskDetails, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BackLogFragmentModel.class);
                        if (obj instanceof BackLogFragmentModel) {
                            BackLogFragmentModel model=(BackLogFragmentModel) obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                     llNodata.setVisibility(View.GONE);
                                    data=model.getResult().getRecords();
                                    adapter=new BackLogFragmentAdapter(data,type);
                                    rcView.setLayoutManager(new LinearLayoutManager(context));
                                    rcView.setAdapter(adapter);
                                    if (adapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                    adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            mPosition=position;
                                            if(type==1){
                                                if (UserData.create(context).get(UserData.ls_xj).equals("0")){
                                                    HiddenDangerinvestigation.actionStart(1,context,defId,
                                                            data.get(position).getRiskPointName(),0,
                                                            data.get(position).getRiskPointId(),checkTableId,data.get(position).getDangerVOList());
                                                }else {
                                                    //扫码   判断风险点id是否一致  获取位置
                                                    checkPermission();
                                                }
                                            }else {
                                                ActivityCheckLog.actionStart(context,data.get(position).getRiskPointId(),checkTableId,defId);
                                            }
                                        }
                                    });
                                } else {
                                    llNodata.setVisibility(View.VISIBLE);
                                    refresh.finishRefreshWithNoMoreData();
                                   // adapter.notifyDataSetChanged();
                                }
                            } else {
                                data.addAll(model.getResult().getRecords());
                                adapter.notifyDataSetChanged();
                                if (adapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishLoadMore();
                refresh.finishRefresh();
            }
        });
    }

    /****权限**/
    private void checkPermission(){
        try{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (PermissionChecker.checkSelfPermission(context, Manifest.permission.CAMERA)!= PermissionChecker.PERMISSION_GRANTED) {
                    // 不相等 请求授权
                    ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CAMERA
                    },REQUEST_CODE);
                }else {
                    //扫描二维码
                    //二维码扫一扫
                    Intent intent = new Intent(getContext(), CaptureActivity.class);
                    intent.putExtra("riskPointId",data.get(mPosition).getRiskPointId());
                    intent.putExtra("defId",defId);
                    intent.putExtra("posi",1);
                    /**ZxingConfig是配置类
                     *可以设置是否显示底部布局，
                     * 闪光灯，相册 是否播放提示音  震动
                     * 设置扫描框颜色等 也可以不传这个参数
                     * */
                    ZxingConfig config = new ZxingConfig();
                    config.setPlayBeep(true);//是否播放扫描声音 默认为true
                    config.setShake(true);//是否震动  默认为true
                    config.setDecodeBarCode(true);//是否扫描条形码 默认为true
                    config.setReactColor(R.color.blue_3B5BEA);//设置扫描框四个角的颜色 默认为白色
                    config.setFrameLineColor(R.color.blue_3B5BEA);//设置扫描框边框颜色 默认无色
                    config.setScanLineColor(R.color.blue_3B5BEA);//设置扫描线的颜色 默认白色
                    config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                    config.setShowFlashLight(true);
                    intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("aaa", "onRequestPermissionsResult: " +
                            "权限申请成功");
                    for (int i : grantResults) {
                        Log.d("aaa", "onRequestPermissionsResult: " + i);
                    }
                    //扫码开始
                    //二维码扫一扫
                    Intent intent = new Intent(getContext(), CaptureActivity.class);
                    intent.putExtra("riskPointId",data.get(mPosition).getRiskPointId());
                    intent.putExtra("defId",defId);
                    intent.putExtra("posi",1);
                    /**ZxingConfig是配置类
                     *可以设置是否显示底部布局，
                     * 闪光灯，相册 是否播放提示音  震动
                     * 设置扫描框颜色等 也可以不传这个参数
                     * */
                    ZxingConfig config = new ZxingConfig();
                    config.setPlayBeep(true);//是否播放扫描声音 默认为true
                    config.setShake(true);//是否震动  默认为true
                    config.setDecodeBarCode(true);//是否扫描条形码 默认为true
                    config.setShowFlashLight(true);
                    config.setReactColor(R.color.blue_3B5BEA);//设置扫描框四个角的颜色 默认为白色
                    config.setFrameLineColor(R.color.blue_3B5BEA);//设置扫描框边框颜色 默认无色
                    config.setScanLineColor(R.color.blue_3B5BEA);//设置扫描线的颜色 默认白色
                    config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                    intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                } else {
                    Toast.makeText(context, "您已拒绝申请权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }



}